package com.pn.taikao.controller;

import com.pn.taikao.dto.ApiResponse;
import com.pn.taikao.dto.ClassQueryRequest;
import com.pn.taikao.dto.CreateResponse;
import com.pn.taikao.dto.PageResult;
import com.pn.taikao.entity.Class;
import com.pn.taikao.service.ClassService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/classes")
public class ClassController {

    private final ClassService classService;

    public ClassController(ClassService classService) {
        this.classService = classService;
    }

    /**
     * 创建班级
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<CreateResponse> create(@RequestBody Class clazz) {
        Long id = classService.createClass(clazz);
        return ApiResponse.success(new CreateResponse(id));
    }

    /**
     * 更新班级
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> update(@PathVariable("id") Long id, @RequestBody Class clazz) {
        clazz.setId(id);
        classService.updateClass(clazz);
        return ApiResponse.success(null);
    }

    /**
     * 删除班级
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> delete(@PathVariable("id") Long id) {
        classService.deleteClass(id);
        return ApiResponse.success(null);
    }

    /**
     * 查询班级详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<Class> detail(@PathVariable("id") Long id) {
        Class clazz = classService.getById(id);
        if (clazz == null) {
            return ApiResponse.error("班级不存在");
        }
        return ApiResponse.success(clazz);
    }

    /**
     * 根据专业ID获取班级列表（不分页，用于下拉选择）
     */
    @GetMapping("/major/{majorId}")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<List<Class>> getByMajor(@PathVariable("majorId") Long majorId) {
        List<Class> classes = classService.getByMajorId(majorId);
        return ApiResponse.success(classes);
    }

    /**
     * 分页查询班级列表
     */
    @PostMapping("/query")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<PageResult<Class>> list(@RequestBody ClassQueryRequest request) {
        // 处理默认值
        int page = (request.getPage() != null && request.getPage() > 0) ? request.getPage() : 1;
        int size = (request.getSize() != null && request.getSize() > 0) ? request.getSize() : 10;
        
        List<Class> data = classService.list(request.getName(), request.getMajorId(), page, size);
        long total = classService.count(request.getName(), request.getMajorId());
        PageResult<Class> pageResult = new PageResult<>(data, total, page, size);
        return ApiResponse.success(pageResult);
    }
}